package app.itgungnir.compose.wan.utils

import android.content.Context
import android.os.Environment
import java.io.File

/**
 * 获取整体缓存大小
 */
fun getTotalCacheSize(context: Context): String {
    var cacheSize = getFolderSize(context.cacheDir)
    if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
        cacheSize += getFolderSize(context.externalCacheDir)
    }
    return getFormatSize(cacheSize)
}

/**
 * 清空方法
 */
suspend fun clearAllCache(context: Context) {
    deleteDir(context.cacheDir)
    if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
        deleteDir(context.externalCacheDir)
    }
    WanDatabase.instance.onUserLogout()
    LocalDataStore.clearAllLocalData()
}

/**
 * 获取文件
 * Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/ 目录，一般放一些长时间保存的数据
 * Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/目录，一般存放临时缓存数据
 */
private fun getFolderSize(file: File?): Long {
    file ?: return 0L
    var size = 0L
    try {
        val fileList = file.listFiles() ?: return 0L
        for (i in fileList.indices) {
            size = if (fileList[i].isDirectory) {
                size + getFolderSize(fileList[i])
            } else {
                size + fileList[i].length()
            }
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    }
    return size
}

/**
 * 格式化单位
 */
private fun getFormatSize(size: Long): String {
    val kb = size / 1024
    val m = (kb / 1024).toInt()
    val kbs = (kb % 1024).toInt()
    return m.toString() + "." + kbs + "M"
}

private fun deleteDir(dir: File?): Boolean {
    dir ?: return false
    if (dir.isDirectory) {
        val children = dir.list() ?: return false
        for (i in children.indices) {
            val success = deleteDir(File(dir, children[i]))
            if (!success) {
                return false
            }
        }
    }
    return dir.delete()
}
